//
//  MCAddFreightViewController.swift
//  StoreManage
//
//  Created by MC on 2018/9/20.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit

class MCAddFreightViewController: MCViewController {
    
    public var model : MCFreightModel?
    
    private var dataArray = [MCChooseAreaModel]()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        managerClosure()
        
        sendNetworking()
    }
    
    // MARK: - Setter & Getter
    lazy var headView: MCAddFreightHeadView = {
        let view = MCAddFreightHeadView()
        return view
    }()
    
    lazy var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
}

//MARK: 通知回调，闭包回调，点击事件
extension MCAddFreightViewController {
    
    @objc func leftClicked() {
    
        UIAlertController.showConfirmOn(self, message: "是否放弃编辑？", confirm: { (_) in
            self.navigationController?.popViewController(animated: true)
        })
    }

    
    func managerClosure() {
        headView.closure = { () -> Void in
            let vc = MCChooseAreaViewController()
            
            vc.selectedArray = self.dataArray
            
            vc.closure = { array in
                self.dataArray = array as! [MCChooseAreaModel]
                self.tableView.reloadData()
            }
            MCPushToViewController(current: self, target: vc)
        }
    }
    
    @objc func rightItemClicked() {
        
        // 保存模板信息
        saveTemplate()
    }
}


//MARK: 网络请求
extension MCAddFreightViewController {
    
    func sendNetworking() {

        if model == nil {
            title = "新增运费模板"
        } else {
            title = "修改运费模板"
            
            let freight = (model?.defaultFreight.intValue)! / 100
            
            let name = model?.name.MCString_prefix(index: 16)
            
            headView.nameView.rightTextField.text = name
            headView.freightView.rightTextField.text = String(freight)
                    

            dataArray = (model?.nonDistributionModels)!
            tableView.reloadData()
        }
    }
    
    
    func saveTemplate() {
        
        let nameStr = headView.nameView.rightTextField.text ?? ""
        let freightStr = headView.freightView.rightTextField.text ?? ""
        
        
        
        if nameStr.isEmpty {
            MCHUD_text(message: "请填写模板名称", view: self.view, delay: 1.2)
            return
        }
        
        if freightStr.isEmpty {
            MCHUD_text(message: "请填写模板运费", view: self.view, delay: 1.2)
            return
        }
        
        let freight = Float(freightStr)! * 100

        let freightTemplateId = model?.freightTemplateId.intValue ?? 0
        
        let para = [
            "defaultFreight"      : freight,
            "name"                : nameStr,
            "nonDistributionList" : progressData(),
            "freightTemplateId"   : freightTemplateId
            ] as [String : Any]
        
        
        MCNetwork.POST(JAVA_modifyFreightTemplate,para,vc: self, success: { (data) in

            var str = ""
            
            if self.model == nil {
                str = "新增运费模板成功"
            } else {
                str = "修改运费模板成功"
            }
            
            
            MCHUD_text(message: str, view: self.view, delay: 1)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                self.navigationController?.popViewController(animated: true)
            })
        }) 
    }
    
    
    func progressData() -> NSArray {
        
        let arrayM = NSMutableArray()
        
        
        for privince in dataArray {
            let privinceModel = privince 
            let provinceId = privinceModel.proId
            
            let array = privince.selectedCityModels.count > 0 ? privince.selectedCityModels : privince.allCityModels
            
            
            for city in array {
                let dictM = NSMutableDictionary.init()
                dictM.setValue(provinceId, forKey: "provinceCode")
                dictM.setValue(city.cityName, forKey: "city")
                arrayM.add(dictM)
            }
        }
        
        return arrayM
    }
}

//MARK: UI的处理,通知的接收
extension MCAddFreightViewController {
    
    func baseSetting() {
        self.title = "新增模板"
        navigationItem.rightBarButtonItem = MCSetBarButtonItem_text("保存", target: self, selector: #selector(rightItemClicked))

        navigationItem.leftBarButtonItem = MCSetBarButtonItem_image(#imageLiteral(resourceName: "Reuse_back"), target: self, selector: #selector(leftClicked), isLeft: true)
    }
    
    
    func initUI() {
        view.addSubview(headView)
        headView.snp.remakeConstraints { (make) ->Void in
            make.left.right.top.equalTo(view)
            make.height.equalTo(160)
        }
        
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) ->Void in
            make.left.right.bottom.equalTo(view)
            make.top.equalTo(headView.snp.bottom)
        }
    }
}

extension MCAddFreightViewController: UITableViewDelegate,UITableViewDataSource {

    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = dataArray[indexPath.row] 
        
        if model.selectedCityModels.count == 0 {
            return model.allCitysHeight + 5
        } else {
            return model.selectedCitysHeight - 56 + 30 + 10
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = MCAddFreightCell.customCell(tableView: tableView)
        cell.model = dataArray[indexPath.row] 
        return cell
    }
}
